package cn.clementine.core.api;

import cn.clementine.core.crud.CustomerCrud;
import cn.clementine.core.entity.sys.Customer;
import cn.clementine.core.vo.LoginResult;
import cn.clementine.core.vo.Result;
import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class Login {
    @Resource
    CustomerCrud customerCrud;

    @PostMapping(value = "/user/login")
    public Result login(@RequestBody Customer customer) {
        if (customer.getPassword() != null && customer.getName() != null) {
            Customer customer_in_db = customerCrud.findByName(customer.getName());
            String pwd = customer_in_db.getPassword();
            if (pwd.equals(SaSecureUtil.sha256(customer.getPassword()))) {
                StpUtil.login(customer_in_db.getId());
                customer_in_db.setPassword("********************************");
                return Result.ok(
                        new LoginResult(StpUtil.getTokenValue(), StpUtil.getTokenTimeout(), customer_in_db), "登陆成功");
            } else {
                return Result.fail("密码错误");
            }
        } else {
            return Result.fail("用户名或密码为空");
        }
    }
}
